package com.fourth_groups.shopping121store.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.fourth_groups.shopping121store.Constants;
import com.fourth_groups.shopping121store.R;
import com.fourth_groups.shopping121store.bean.GoodsDetailBean;
import com.fourth_groups.shopping121store.http.OkHttpClientUtils;
import com.fourth_groups.shopping121store.ui.category.activity.CategoryChatServiceActivity;
import com.fourth_groups.shopping121store.ui.category.activity.CategoryIntoStoreActivity;
import com.fourth_groups.shopping121store.ui.category.adapter.GoodsDetailRecycleAdapter;
import com.fourth_groups.shopping121store.ui.category.adapter.commonadapter.CommonAdapter;
import com.fourth_groups.shopping121store.ui.category.adapter.commonadapter.ShowImgPagerAdapter;
import com.fourth_groups.shopping121store.ui.category.adapter.commonadapter.ViewHolder;
import com.fourth_groups.shopping121store.ui.category.customview.GoodsContentPage;
import com.fourth_groups.shopping121store.ui.category.customview.GoodsDetailInfoPage;
import com.fourth_groups.shopping121store.ui.category.customview.GoodsSnapPageLayout;
import com.fourth_groups.shopping121store.utils.GsonImpl;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class GoodsDetailActivity extends AppCompatActivity {

    private GoodsDetailBean goodsDetailBeen;
    private static final int SUCCESS = 1;
    private List<ImageView> imageViewsTop = new ArrayList<>();

    private GoodsSnapPageLayout goodsSnapPageLayout = null;
    private GoodsContentPage bottomPage = null;
    private GoodsDetailInfoPage topPage = null;
    private ShowImgPagerAdapter vpTopAdapter;
    private ViewPager vpTop;
    private TextView tvName;
    private TextView tvTitle;
    private TextView tvNowPrice;
    private TextView tvBeforePrice;
    private TextView tvFencheng;
    private TextView tvShareMsg1;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCESS:
                    goodsDetailBeen = (GoodsDetailBean) msg.obj;

                    getImageViews();

                    init();
                    break;
            }
        }
    };
    private TextView tvSalesPrice;
    private RecyclerView rvShare;
    private ImageView ivStoreLogo;
    private ImageView ivStoreLogo2;
    private TextView tvStoreName;
    //    private WebView wvShwoDetail;
    private ListView mlv;
    private CommonAdapter<String> lvadapter;
    private Button btChat;
    private Button btStore;
    private ImageView ivShare;
    private Toolbar mTb;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_goods_detail);

        //找到自定义view上下滑动切换页面的布局
        goodsSnapPageLayout = (GoodsSnapPageLayout) findViewById(R.id.flipLayout);
        //得到第一页的布局
        topPage = new GoodsDetailInfoPage(GoodsDetailActivity.this, getLayoutInflater().inflate(R.layout.goods_detail_layout, null));
        //得到第二页的布局
        bottomPage = new GoodsContentPage(GoodsDetailActivity.this, getLayoutInflater().inflate(R.layout.goods_content_page, null));
        //将第一页与第二页的布局添加到自定义的布局中
        goodsSnapPageLayout.setSnapPages(topPage, bottomPage);

        //初始化控件
        initView();

        //创建布局管理器
        LinearLayoutManager manager = new LinearLayoutManager(this);
        //设置方向
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        //必须设置布局管理器!
        rvShare.setLayoutManager(manager);
        //得到传递过来的id
        Intent intent = getIntent();
        int id = intent.getIntExtra("id", 0);
        String url = Constants.ALL_GOODS_DETAIL_URL.replace("%d", Integer.toString(id));
        //下载数据并解析
        loadData(url);

        lvadapter = new CommonAdapter<String>(GoodsDetailActivity.this, R.layout.list_item_goods_detail) {
            @Override
            public void convert(ViewHolder helper, String item, int position) {
                super.convert(helper, item, position);
                helper.setImageByUrl(GoodsDetailActivity.this, R.id.iv_item_goods_detail, item);
            }
        };
        mlv.setAdapter(lvadapter);

    }

    //初始化控件
    private void initView() {
        vpTop = (ViewPager) findViewById(R.id.vp_top_goods_detail);
        rvShare = (RecyclerView) findViewById(R.id.recycleview_goods_detail);
        tvName = (TextView) findViewById(R.id.tv_name_goods_detail);
        tvTitle = (TextView) findViewById(R.id.tv_title_goods_detail);
        tvNowPrice = (TextView) findViewById(R.id.tv_now_price_goods_detail);
        tvBeforePrice = (TextView) findViewById(R.id.tv_before_price_goods_detail);
        tvFencheng = (TextView) findViewById(R.id.tv_fencheng_category_goods_detail);
        tvShareMsg1 = (TextView) findViewById(R.id.tv_share_msg1);
        tvSalesPrice = (TextView) findViewById(R.id.tv_price_sales_goods_detail);
        ivStoreLogo = (ImageView) findViewById(R.id.iv_store_logo_goods_detail);
        ivStoreLogo2 = (ImageView) findViewById(R.id.iv_store_logo2_goods_detail);
        tvStoreName = (TextView) findViewById(R.id.tv_store_name_goods_detail);
        mlv = (ListView) findViewById(R.id.lv_goods_detail);
        btChat = (Button) findViewById(R.id.bt_chat_service_goods_detail);
        btStore = (Button) findViewById(R.id.bt_into_store_goods_detail);
        ivShare = (ImageView) findViewById(R.id.iv_share_goods_detail);
        mTb = (Toolbar) findViewById(R.id.tbar_goods_detail);
    }

    //根据图片的数量，得到顶部viewPager图片滑动的ImageView的集合
    private void getImageViews() {

        for (int i = 0; i < goodsDetailBeen.getData().getBanners().size(); i++) {
            ImageView imageView = new ImageView(this);
            Glide.with(this).load(goodsDetailBeen.getData().getBanners().get(i).getImage()).into(imageView);
            imageViewsTop.add(imageView);
        }
    }

    //下载数据
    private void loadData(String url) {
        OkHttpClientUtils.getDataAsync(this, url, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Toast.makeText(GoodsDetailActivity.this, "下载失败，请检查您的网络！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String json = response.body().string();
                //Gson解析数据，返回一个bean
                GoodsDetailBean bean = GsonImpl.get().toObject(json, GoodsDetailBean.class);
                Message message = new Message();
                message.what = SUCCESS;
                message.obj = bean;
                //利用mHandler将下载并解析完的数据发送给主线程
                mHandler.sendMessage(message);
            }
        }, new Object());
    }


    //初始化绑定个控件对应的数据
    protected void init() {
        //设置顶部图片滚动viewpager当前的位置
        vpTop.setCurrentItem(1000);
        //创建适配器
        vpTopAdapter = new ShowImgPagerAdapter(imageViewsTop);
        vpTop.setAdapter(vpTopAdapter);
        vpTopAdapter.notifyDataSetChanged();

        //设置分享部分RecycleView的适配器
        rvShare.setAdapter(new GoodsDetailRecycleAdapter(GoodsDetailActivity.this, goodsDetailBeen.getData().getDetails_img()));

        tvName.setText(goodsDetailBeen.getData().getName());
        tvTitle.setText(goodsDetailBeen.getData().getTitle());
        tvNowPrice.setText("￥" + goodsDetailBeen.getData().getPrice());
        tvSalesPrice.setText(goodsDetailBeen.getData().getPrice());
        tvBeforePrice.setText("￥" + goodsDetailBeen.getData().getMarket_price());
        tvFencheng.setText(goodsDetailBeen.getData().getRebate());
        tvShareMsg1.setText(goodsDetailBeen.getData().getName());
        //得到商店的bean
        GoodsDetailBean.DataBean.BlockBean.ItemsBean store = goodsDetailBeen.getData().getBlock().get(5).getItems().get(0);
        //设置商店的图标
        Glide.with(this).load(store.getImage()).asBitmap().into(ivStoreLogo);
        Glide.with(this).load(store.getImage()).asBitmap().into(ivStoreLogo2);
        //设置商店的名称
        tvStoreName.setText(store.getName());

        //设置第货物图文详情页的的图片的图片
        lvadapter.setData(goodsDetailBeen.getData().getDetails_img());
        lvadapter.notifyDataSetChanged();

        btChat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GoodsDetailActivity.this, CategoryChatServiceActivity.class);
//                intent.putExtra("chat",goodsDetailBeen.getData().getBlock().get(5).getItems().get(0).getService().getChat_url());
                startActivity(intent);
            }
        });

        btStore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GoodsDetailActivity.this, CategoryIntoStoreActivity.class);
                intent.putExtra("chat",goodsDetailBeen.getData().getBlock().get(5).getItems().get(0).getUrl());
                startActivity(intent);
            }
        });

        ivShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置分享的平台
                SHARE_MEDIA[] list = new SHARE_MEDIA[]{SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA,
                        SHARE_MEDIA.QQ,SHARE_MEDIA.EMAIL, SHARE_MEDIA.SMS, SHARE_MEDIA.RENREN
                };

                new ShareAction(GoodsDetailActivity.this)
                        .setDisplayList(list)//设置分享的平台列表
                        .withText("分享的内容")//分享的内容
                        .withTitle("分享的标题")//分享的标题
                        .withMedia(new UMImage(GoodsDetailActivity.this, R.mipmap.ic_launcher))//多媒体:图片,音频,视频,表情等
                        //.withTargetUrl(url)//分享一个链接
                        //.addButton()
                        .setCallback(umShareListener)//分享的监听
                        .open();//打开分享面板
            }
        });

        mTb.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    //回调监听
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {

            Toast.makeText(GoodsDetailActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(GoodsDetailActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(GoodsDetailActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    public void share(View view) {
        //设置分享的平台
        SHARE_MEDIA[] list = new SHARE_MEDIA[]{SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA,
                SHARE_MEDIA.QQ,SHARE_MEDIA.EMAIL, SHARE_MEDIA.SMS, SHARE_MEDIA.RENREN
        };

        new ShareAction(GoodsDetailActivity.this)
                .setDisplayList(list)//设置分享的平台列表
                .withText("分享的内容")//分享的内容
                .withTitle("分享的标题")//分享的标题
                .withMedia(new UMImage(GoodsDetailActivity.this, R.mipmap.ic_launcher))//多媒体:图片,音频,视频,表情等
                //.withTargetUrl(url)//分享一个链接
                //.addButton()
                .setCallback(umShareListener)//分享的监听
                .open();//打开分享面板
    }

    public void skipCar(View view) {
        Intent intent = new Intent(GoodsDetailActivity.this,MainActivity.class);
        intent.putExtra("flag","car");
        startActivity(intent);
    }


}
